package com.guige.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Configuration
public class RestTemplateConfig {

	private static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 100;

	private static final int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 10;
	
	private static final int DEFAULT_MAX_TIME_OUT = 3000;

	@Value("${guige.http.proxy.ip:}")
	String ip;

	@Value("${guige.http.proxy.port:}")
	String port;
	
	private static final Logger LOG = Logger.getLogger(RestTemplateConfig.class);
	
	@Bean
	public RestTemplate restTemplate() {
		return new RestTemplate(httpRequestFactory());
	}
	
	@Bean
	public ClientHttpRequestFactory httpRequestFactory(){
		HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
		SocketConfig socketConfig = SocketConfig
				.custom()
				.setSoKeepAlive(false)
				.setTcpNoDelay(true)
				.build();
		PoolingHttpClientConnectionManager pm = new PoolingHttpClientConnectionManager();
		pm.setDefaultSocketConfig(socketConfig);
		pm.closeIdleConnections(DEFAULT_MAX_TIME_OUT, TimeUnit.MICROSECONDS);
		pm.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
		pm.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
		
		HttpHost proxy = null;
		try {
			if(StringUtils.isNotBlank(ip) && StringUtils.isNotBlank(port)) {
				LOG.info("set proxy for RestTemplate, proxy ip:" +ip + " port:" + port);
				proxy = new HttpHost(ip, Integer.parseInt(port));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		CloseableHttpClient httpClient = HttpClientBuilder.create()
				.setConnectionManager(pm)
				.setProxy(proxy)
				.build();
		requestFactory.setHttpClient(httpClient);
		return requestFactory;
	}
}
